数组扁平化
function flatten(arr){
let result = [];
for(let i = 0; i <= arr.length - 1; i ++){
if(Array.isArray(arr[i])){
result = result.concat(flatten(arr[i]));
}else{
result.push(arr[i]);
}
}
return result;
}
console.log(flatten([1,[2,[3,4],5]]));
- 若数组的元素都是数字/都是字符串的话,可以考虑toString方法
function flatten(arr){
return arr.toString().split(",").map(item=>{
return +item;
//单运算符+会把字符串转化为数字
})
}
console.log(flatten(['1',[2,[3,4],5]]));
function flatten(arr){
return arr.reduce((pre,cur)=>{
return pre.concat(Array.isArray(cur)?flatten(cur):cur)
},[])
}
console.log(flatten(['1',[2,[3,4],5]]));
function flatten(arr){
while(arr.some(item=>Array.isArray(item))){
//arr.some遍历数组的每一项
arr = [].concat(...arr);
}
return arr;
}
console.log(flatten(['1',[2,[3,4],5]]));